package com.yl.zqy.utils;

import cn.hutool.core.util.IdUtil;
import com.yl.zqy.entity.sys.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Description 文件上传-工具类
 * @Author liang.yu
 * @Date 2024/6/20 21:19
 */
@Slf4j
public class ZQYFileUtils {
    @Value("${zqy.upload.files.path}")
    private String uploadPath;
    public static void checkFileCatalog(String path) {
        File file = new File(path);
        // 判断文件夹是否存在，不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static SysFile getFileObject(String path, MultipartFile poster) throws IOException {
        // 判断文件夹是否存在，不存在则创建
        checkFileCatalog(path);
        //获取文件名原始名称
        String originalFileName = poster.getOriginalFilename();
        int index = StringUtils.lastIndexOf(originalFileName, ".") + 1;
        String fileType = "";
        if (index > 1 && StringUtils.length(originalFileName) > index) fileType = originalFileName.substring(index);
        //获取文件 转码名称
        String fileName = IdUtil.simpleUUID() + "." + fileType;
        String filePath = path + fileName;
        File file = new File(filePath);
        log.info("文件名称：{}" , file.getName());
        log.info("文件路径：{}" , file.getAbsoluteFile());
        FileUtils.copyInputStreamToFile(poster.getInputStream(), file);
        double fileSize = poster.getSize() / (1024.0 * 1024.0);
        SysFile  result = new SysFile();
        result.setFileOriginalName(originalFileName);
        result.setFileName(fileName);
        result.setFileAbsolutePath(filePath);
        result.setFileSize(BigDecimal.valueOf(fileSize));
        result.setFileType(fileType);
        return result;
    }
}
